<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择题目类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.question_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目标题" prop="type">
        <el-input v-model="queryParams.content" placeholder="请输入题目标题">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['psedu-exam:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['psedu-exam:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['psedu-exam:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['psedu-exam:question:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目ID" align="center" prop="questionId" width="80"/>
      <el-table-column label="题目内容" align="left" prop="content">
        <template slot-scope="scope">
          <div v-html="scope.row.content"/>
        </template>
      </el-table-column>
      <el-table-column label="题目类型" align="center" prop="type" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.question_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="难度等级" align="center" prop="difficultyRating"  width="80"/>
      <el-table-column label="适用对象" align="center" width="120">
        <template slot-scope="scope">
          {{suitData2Str(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column label="适用于正式考试" align="center" prop="realExam"  width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.realExam === 1">正式考试</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['psedu-exam:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['psedu-exam:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改候选题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :fullscreen="needFull">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择题目类型">
            <el-option
              v-for="dict in dict.type.question_type"
              :key="dict.value"
              :label="dict.label"
:value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item :label="'选项' +(index +1)"
                      v-for="(answerOption, index) in form.answerOptions"
                      class="option"
                      :rules="{validator: validateOption}"
                      :prop="'answerOptions.' +index +'.content'">
          <el-input v-model="form.answerOptions[index].content" :placeholder="'选项' +(index +1)" >
            <div slot="prepend"
                 :class="{
                  'is-correct-option': answerOption.isCorrect,
                  'is-error-option': !answerOption.isCorrect
                  }"
                 @click="turnCorrect(answerOption)"
            >
              <i class="el-icon-circle-check" v-if="answerOption.isCorrect"/>
              <i class="el-icon-circle-close" v-if="!answerOption.isCorrect"/>
            </div>
            <el-button slot="append" icon="el-icon-delete-solid" @click="deleteOption(index)"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-plus" style="width: 100%"  @click="addEmptyOption()">添加新选项</el-button>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="难度等级" prop="difficultyRating">
          <el-rate
            v-model="form.difficultyRating"
            :colors="rateColors">
          </el-rate>
        </el-form-item>
        <el-form-item label="适用对象">
          <el-checkbox-group v-model="suitList" @change="changeSuit"  size="mini">
            <el-checkbox-button :label="0" :key="0">入党积极分子</el-checkbox-button>
            <el-checkbox-button :label="1" :key="1">发展对象</el-checkbox-button>
            <el-checkbox-button :label="2" :key="2">预备党员</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="适用正式考试">
          <el-switch
            v-model="form.realExam"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="0"
            :active-value="1"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/psedu-exam/question";

export default {
  name: "Question",
  dicts: ['question_type'],
  data() {
    var validateOption = (rule, value, callback) => {
      let answerOptions = this.form.answerOptions;
      let type = this.form.type;
      let optionCount = 0;
      let correctCount = 0;
      answerOptions.forEach(option => {
        if(option.content != null && option.content !== '') {
          if(option.content.length < 1) {
            callback(new Error("选项长度小于1"));
          }
          optionCount++;
          if(option.isCorrect === 1) {
            correctCount++;
          }
        }
      })
      if(correctCount === 0) {
        callback(new Error("该题未设置答案"));
      }
      if(type === 1 && correctCount !== 1) {
        callback(new Error("单选题答案有且仅有一个"));
      }
      if(type === 2) {
        if(correctCount !== 1) {
          callback(new Error("判断题答案有且仅有一个"));
        }
        if(optionCount !== 2) {
          callback(new Error("判断题选项应该只有两个"));
        }
      }
      if(type === 3 && correctCount <= 1) {
        callback(new Error("多选题答案应该有多个答案"));
      }
      callback();
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 候选题目表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        content: null,
        difficultyRating: null,
        suitAct: null,
        suitDev: null,
        suitPre: null,
        realExam: null,
      },
      suitList: [],
      // 2,4,5
      rateColors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      // 表单参数
      form: {
        answerOptions: []
      },
      // 表单校验
      validateOption,
      rules: {
        type: [
          {required: true, message: '题目类型需指定'}
        ],
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' },
          { min: 8, message: '题目长度小于 8 个字符', trigger: 'blur' }
        ],
        answerOption: [
          { validator: validateOption}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
  },
  computed: {
    needFull() {
      return document.body.clientWidth < 1200;
    }
  },
  methods: {
    /** 查询候选题目列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 改变适用对象 */
    changeSuit(newListValue) {
      this.form.suitAct = 0;
      this.form.suitDev = 0;
      this.form.suitPre = 0;
      newListValue.forEach( value => {
        if(value === 0) {
          this.form.suitAct = 1;
        } else if(value === 1) {
          this.form.suitDev = 1;
        } else if(value === 2) {
          this.form.suitPre = 1;
        }
      })
    },
    /** suitDev 等 加入选项List */
    suitData2List() {
      this.suitList = [];
      if(this.form.suitAct === 1) {
        this.suitList.push(0);
      }
      if(this.form.suitDev === 1) {
        this.suitList.push(1);
      }
      if(this.form.suitPre === 1) {
        this.suitList.push(2);
      }
    },
    // suitData to String
    suitData2Str(row) {
      let list = [];
      if(row.suitAct === 1) {
        list.push("积极分子");
      }
      if(row.suitDev === 1) {
        list.push("发展对象");
      }
      if(row.suitPre === 1) {
        list.push("预备党员");
      }
      return list.join("、");
    },
    turnCorrect(answerOption) {
      if(answerOption.isCorrect === 0) {
        answerOption.isCorrect = 1;
      } else {
        answerOption.isCorrect = 0;
      }
      this.$refs['form'].validate((valid) => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionId: null,
        type: null,
        content: null,
        difficultyRating: null,
        suitAct: null,
        suitDev: null,
        suitPre: null,
        realExam: null,
        answerOptions: []
      };
      this.suitList = [];
      this.initOptionsData();
      this.resetForm("form");
    },
    initOptionsData() {
      for(let i = 0 ; i < 5; i++) {
        this.form.answerOptions.push({
          content: '',
          sort: i,
          isCorrect: 0,
          imageUrl: "",
          analysis: ""
        })
      }
    },
    // 补全空选项列表
    fillEmptyOptions() {
      let options = this.form.answerOptions;
      while(options.length < 5) {
        options.push({isCorrect: 0});
      }
    },
    addEmptyOption() {
      this.form.answerOptions.push({isCorrect: 0});
    },
    deleteOption(index) {
      this.form.answerOptions.splice(index, 1);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.questionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加候选题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const questionId = row.questionId || this.ids
      getQuestion(questionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改候选题目";
        this.fillEmptyOptions();
        this.suitData2List();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.questionId != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionIds = row.questionId || this.ids;
      this.$modal.confirm('是否确认删除候选题目编号为"' + questionIds + '"的数据项？').then(function() {
        return delQuestion(questionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('psedu-exam/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
  /deep/ .option .el-input-group__prepend {
    padding: 0 4px;
  }
  .is-correct-option {
    color: lawngreen;
    font-size: 27px;
  }
  .is-error-option {
    color: red;
    font-size: 27px;
  }
  .el-rate {
    display: inline-block;

  }
</style>
